package lesson.test1;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 获取Constructor对象并创建对象
 */

public class ReflectDemo2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //T newInstance(Object... initargs)：根据指定的构造方法创建对象
        //method1();
        //method2();
        //method3();
       method4();

    }
    //获取一个私有的构造方法并创建对象
    private static void method4() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class classz = Class.forName("lesson.test1.Student");
        Constructor constructor = classz.getDeclaredConstructor(String.class);
        constructor.setAccessible(true);
        Student stu = (Student) constructor.newInstance("张三");
        System.out.println(stu);
    }

    // 简化方式 (简化空参构造创建对象)
    private static void method3() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class classz = Class.forName("lesson.test1.Student");
        Student stu = (Student) classz.newInstance();
        System.out.println(stu);
    }

    // 通过有参构造创建对象
    private static void method2() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class classz = Class.forName("lesson.test1.Student");
        Constructor constructor = classz.getConstructor(String.class,int.class);
        Student stu = (Student) constructor.newInstance("张三",23);
        System.out.println(stu);
    }

    // 通过空参构造创建对象
    private static void method1() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class classz = Class.forName("lesson.test1.Student");
        Constructor constructor = classz.getConstructor();
        Student stu = (Student) constructor.newInstance();
        System.out.println(stu);
    }
}
